package com.theexceptions.todo.controller;

import java.util.Calendar;

import com.theexceptions.todo.model.DatabaseHelper;
import com.theexceptions.todo.model.IPersister;
import com.theexceptions.todo.model.Location;
import com.theexceptions.todo.model.Reminder;
import com.theexceptions.todo.model.Repeat;

/**
 * A controller that handles adding tasks.
 * 
 * @author Justian Meyer
 */
public class AddTaskController extends Controller {

	public static int ADD_TASK_SUCCESS = 1;
	public static int ADD_TASK_ERROR = -1;
	protected static Location location = null;

	/**
	 * Attempts to add a new task into the system with the provided information
	 * and returns an integer detailing the success of the action.
	 * 
	 * TODO change parameters to not be model objects.
	 * 
	 * @param userID
	 * @param name
	 * @param time
	 * @param location Task location
	 * @param repeat Whether or not and how often task repeats
	 * @param reminder Reminder associated with task
	 * @param category Task category
	 * @param description Task description
	 * @return ADD_TASK_ERROR if an error occurs trying to add the task,
	 *         ADD_TASK_SUCCESS if task added successfully
	 */
	public static int addTask(String name, Calendar time, Repeat repeat, Reminder reminder, String category,
			String description) {

		IPersister dh = new DatabaseHelper(context);
		long userID = currentUser.getUserID();
		Long locID = null;
		
		if (location != null) {
			locID = (location.getID() >= 0) ? location.getID() : null;

			if (location.getID() < 0) {
				long locRowID = dh.insertLocation(location.getName(), currentUser.getUserID(),
						location.getLatitude(), location.getLongitude());

				if (locRowID > 0)
					locID = locRowID;
			}
		}
		
		long rowID = dh.insertTask(userID, name, time, locID, null, category, description);

		if (rowID < 0)
			return ADD_TASK_ERROR;

		return ADD_TASK_SUCCESS;
	}

	/**
	 * Returns the location currently being used.
	 * 
	 * @return
	 */
	public static Location getLocation() {
		return location;
	}

	/**
	 * Resets the location currently being used.
	 */
	public static void resetLocation() {
		location = null;
	}
	
	/**
	 * Sets the location currently being used.
	 */
	protected static void setLocation(Location loc) {
		location = loc;
	}

}
